package priv.happy.mealpickpro.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import priv.happy.mealpickpro.domain.Tag;
import priv.happy.mealpickpro.dto.UserTagCount;
import priv.happy.mealpickpro.mapper.TagMapper;
import priv.happy.mealpickpro.service.TagService;
import priv.happy.mealpickpro.service.UserMealService;

import java.time.Duration;
import java.util.List;
import java.util.Objects;

/**
 * @author HAPPY
 * @description 针对表【tag】的数据库操作Service实现
 * @createDate 2023-07-02 11:23:42
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
        implements TagService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    TagMapper tagMapper;
    @Autowired
    UserMealService userMealService;

    @Override
    public List<Tag> getFoodTagList(Integer foodId) {

        return tagMapper.selectFoodTagList(foodId);
    }

    @Override
    public List<Tag> getAllTags(Integer userId) {
        List<Tag> tagList = null;
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String tagListStr = operations.get("mealpickpro:tags:" + userId);
        if (tagListStr == null || tagListStr.isEmpty() || "[]".equals(tagListStr)) {
            tagList = list(new QueryWrapper<Tag>().eq("post_user_id", userId));
            // 将tag存入redids，默认一个小时失效
            operations.set("mealpickpro:tags:" + userId, JSONUtil.toJsonStr(tagList), Duration.ofSeconds(60 * 60));
        } else {
            tagList = JSONUtil.toList(tagListStr, Tag.class);
        }

        return tagList;
    }

    @Override
    public boolean removeTagById(Integer tagId, Integer userId) {
        // 普通用户仅能删除自己上传的标签，其他人上传的标签无法删除
        if (getById(tagId) != null && (Objects.equals(getById(tagId).getPostUserId(), userId) || "管理员".equals(userMealService.getById(userId).getRole()))) {
            try {
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set("mealpickpro:tags:" + userId, "", Duration.ofSeconds(1));
                // 删除标签
                removeById(tagId);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }

    @Override
    public List<UserTagCount> countUserTags() {
        return tagMapper.countUserTags();
    }
}




